#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@File    ：sms_un_comp_reg_v1.py
@IDE     ：PyCharm 
@Author  ：lmy
@Date    ：2024/8/6 21:26 
'''

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@File    ：sms_mx_comp_reg.py
@IDE     ：PyCharm 
@Author  ：lmy
@Date    ：2024/7/27 11:55 
'''
import os
import json
from pathlib import Path
import pandas as pd
from feature_set.sms.utils.data_utils import *


class SmsUnCompRegV1:

    def __init__(self,conf_path,country_code,bank_words,carrier,long_words):
        df_comp = pd.read_csv(os.path.join(conf_path, 'comp_all.txt'), header=None)
        df_loan = pd.read_csv(os.path.join(conf_path, 'loanword_all.txt'), header=None)
        df_sender = pd.read_csv(os.path.join(conf_path, 'sender_all.txt'), header=None)
        df_url = pd.read_csv(os.path.join(conf_path, 'url_all.txt'), header=None)
        loan_lst = [i.lower() for i in df_loan[0].to_list()]
        url_lst = df_url[0].to_list()
        sender_lst = [int(i) for i in df_sender[0].to_list()]
        comp_lst = [i.lower() for i in df_comp[0].to_list()]
        self.country_code = country_code

        self.comp_conf = {
            "loan_lst": loan_lst,
            "url_lst": url_lst,
            "sender_lst": sender_lst,
            "comp_lst": comp_lst,
            "stopwords": STOPWORD_ES,
            "bank_words": bank_words,
            "carrier": carrier,
            "long_words": long_words
        }

    def loan_url_find(self, body):
        """
        短信内容中是否含有竞品url
        body:短信内容
        """
        for i in self.comp_conf["url_lst"]:
            if i in body.lower():
                return i
        return ''

    def loan_comp_find(self, body):
        """
        body:短信内容
        返回竞品名称
        """
        for i in self.comp_conf["comp_lst"]:
            if len(i.split(' ')) > 1 or len(i) > 6:
                if i in body:
                    return i
            elif len(i.split(' ')) == 1:
                if i in body.split(' ')[0]:
                    return i
            else:
                comp = extract_contents_in_brackets(body.strip())
                comp_name = comp[0]
                if len(comp_name) > 0 and comp_name == i:
                    return comp_name

        return ''

    def loan_word_find(self, body, word_lst):
        """
        body:string,短信内容
        loan_lst:list,贷款关键词
        返回竞品关键词
        """

        match_loan = 0
        loanword = []
        for lw in self.comp_conf["loan_lst"]:

            # 单个词的话看个数
            if len(lw.split(' ')) == 1 or lw[0] == ' ':
                if lw in body:
                    loanword.append(lw)
                    match_loan = match_loan + 1
                    if match_loan > 2:
                        return loanword
            # 词组(相邻不超过5)的话命中则算竞品
            else:
                drop_stop = [i for i in lw.split(' ') if i not in self.comp_conf["stopwords"]]  # 竞品词组的去停用词
                res = []  # 每个词在短信分词中的index，形如[[],...,[]]
                for w in drop_stop:
                    indices = [idx for idx, item in enumerate(word_lst) if w in item]
                    if len(indices) > 0:
                        res.append(indices)

                if len(res) < 2:
                    continue
                else:
                    for index, arr in enumerate(res):
                        others = sorted(list(chain.from_iterable(res[:index] + res[index + 1:])))
                        diff_res = [abs(others[0] - arr[0]), abs(others[-1] - arr[0]), abs(others[0] - arr[-1]),
                                    abs(others[-1] - arr[-1])]
                        if min(diff_res) < 6:
                            return [lw]
        return []

    def loan_word_find2(self, body):
        """
        简单命中即可，辅助url和sender进行竞品识别
        body:string,短信内容
        """
        match_loan = 0
        # loanword 是否命中
        loanword = []

        for lw in self.comp_conf["loan_lst"]:
            if lw in body:
                loanword.append(lw)
                match_loan = match_loan + 1
                if match_loan > 1:
                    return loanword
        return []

    def improve_acc(self, row):
        """
         # 提高竞品识别准确率 去除含银行以及运营商
        row:每行数据，包含flag,loan_comp等
        """

        if row['flag'] // 10 % 10 == 1:
            # 命中竞品则直接返回
            return row['flag']
        for i in self.comp_conf['long_words']:
            if i in row['body']:
                return 0
        if set(row['word']) & set(self.comp_conf['bank_words'] + self.comp_conf['carrier']):
            return 0
        return row['flag']

    def is_competition(self, df):
        """"
        user_sms：处理好后的dataframe
        """
        columns_lst = df.columns.to_list() + ['loan_word', 'loan_word2', 'loan_comp', 'loan_url', 'loan_sender',
                                              'flag']
        df_check = df[df['is_digit'] == 1]  # sender为数字
        if df_check.shape[0] != 0:
            df_check['loan_word'] = df_check.apply(lambda x: self.loan_word_find(x['body'], x['word']), axis=1)
            df_check['loan_word2'] = df_check['body'].apply(self.loan_word_find2)
            df_check['loan_comp'] = df_check['body'].apply(self.loan_comp_find)
            df_check['loan_url'] = df_check['body'].apply(self.loan_url_find)
            df_check['loan_sender'] = df_check['sender'].apply(
                lambda x: x if int(x) in self.comp_conf["sender_lst"] else '')

            df_check['flag'] = 0
            df_check['flag'] = df_check.apply(
                lambda x: x['flag'] + 1 if str(x['loan_sender']) != '' and x['loan_word2'] != [] else x['flag'], axis=1)
            df_check['flag'] = df_check.apply(lambda x: x['flag'] + 10 if x['loan_comp'] != '' else x['flag'], axis=1)
            df_check['flag'] = df_check.apply(
                lambda x: x['flag'] + 100 if x['loan_url'] != '' and x['loan_word2'] != [] else x['flag'], axis=1)
            df_check['flag'] = df_check.apply(lambda x: x['flag'] + 1000 if x['loan_word'] != [] else x['flag'], axis=1)

            df_check['flag'] = df_check.apply(lambda x: self.improve_acc(x), axis=1)

            df_check = df_check[df_check['flag'] != 0]

        else:
            df_check = pd.DataFrame(columns=columns_lst)

        return df_check
